{* $Id$ *}
{include_core file="admin/lib/header.html" title="商品展示"}
<style>
    #icontable {
        width: 560px;
        margin-top: 20px;
        padding: 0px;
    }

    #icontable th, #icontable td {
        border: 1px solid #D7D7D7;
        text-align: center;
        padding: 0px 0px 0px 0px;
    }

    #icontable tr {
        height: 25px;
    }

    #icontable th {
        height: 25px;
        background: #EDEDED;
        line-height: 25px;
    }

    #icontable td {
        height: 30px;
        line-height: 30px;
    }

    #icontable td div {
        height: 20px;
        margin-top: 5px;
        margin-left: 5px;
        float: left;
    }

    #icontable td div a {
        padding: 3px;
    }

    #icontable td div img {
        width: 30px;
        height: 30px;
    }

    #skutable {
        width: auto;
        margin-top: 20px;
        padding: 0px;
    }

    #skutable th, #skutable td {
        border: 1px solid #D7D7D7;
        text-align: center;
        padding: 0px 0px 0px 0px;
    }

    #skutable tr {
        height: 25px;
    }

    #skutable th {
        height: 25px;
        background: #EDEDED;
        line-height: 25px;
    }

    #skutable td {
        height: 30px;
        line-height: 30px;
    }

    #skutable td div {
        height: 20px;
        width: auto;
        margin-top: 5px;
        margin-left: 5px;
        float: left;
    }

    #skutable td div a {
        padding: 3px;
    }

    #skutable td div img {
        width: 30px;
        height: 30px;
    }

    #skutable td input {
        width: 50px;
    }

    .picBox {
        width: 600px;
        height: auto;
        clear: both;
    }

    .picBox div {
        width: 90px;
        height: 90px;
        border: 1px solid #D7D7D7;
        background: #EFEFEF;
        float: left;
        margin-right: 5px;
        margin-top: 10px;
        text-align: center;
        position: relative;
    }

    .picBox div img {
        width: 90px;
        height: 90px;
    }

    .picBox > div .delete-btn {
        position: absolute;
        top: 0px;
        right: 0px;
        width: 20px;
        height: 20px;
        background: rgba(0, 0, 0, 0.5);
        display: none;
        color: #FFFFFF;
        line-height: 20px;
        text-align: center;
        border-radius: 50%;
    }

    .picBox > div:hover .delete-btn {
        display: block;
    }

    .picBox > div .delete-btn:hover {
        background: rgba(0, 0, 0, 0.7);
        cursor: pointer;
    }

    .picBox > div .main-btn {
        position: absolute;
        top: 0px;
        right: 25px;
        background: rgba(0, 0, 0, 0.5);
        color: #FFFFFF;
        border-radius: 10px;
        line-height: 20px;
        height: 20px;
        font-size: 12px;
        padding: 0px 5px;
        display: none;
    }

    .picBox > div:hover .main-btn {
        display: block;
    }

    .picBox > div .main-btn:hover {
        background: rgba(0, 0, 0, 0.7);
        cursor: pointer;
    }

    .stock-input:readonly {
        background: #EFEFEF;
    }

    #file_upload {
        position: relative;
        left: 0px;
        border: 1px solid #287ebd;
        text-align: center;
        background: #357ebd;
        color: #FFF;
    }

    #file_upload object {
        left: 0px;
    }

    .cover-style {
        display: block;
        position: absolute;
        bottom: 0px;
        background: rgba(0, 0, 0, 0.8);
        color: #FFF;
        height: 25px;
        width: 90px;
        line-height: 25px;
        text-align: center;
    }
</style>
<div class="page-header border-bottom clearfix">
    <h2 class="left">商品管理<span>{if $info}编辑{else}添加{/if}商品</span></h2>
    <a href="{AnUrl('goods/admin')}" class="btn btn-default btn-sm right">&lt;&nbsp;返回商品列表</a>
</div>
<!--start:商品新增-->
<div class="add-form">
    <div class="js_goodsMain">
        <form class="js_creatForm" action="{AnUrl('goods/admin/save')}" method="post" enctype="multipart/form-data">
            <input type="hidden" name="id" value="{$goods_info.id}">
            <table class="table" cellpadding="0" cellspacing="0">
                <tr>
                    <th>
                        <label class="add-f-label">商品分类：</label>
                    </th>
                    <td>
                        <select class="add-f-slt1 js_category" name="info[category_id]">
                            <option value=""{if empty($goods_info.category_id)} selected="selected"{/if}>请选择商品分类</option>
                            {foreach $category_list as $k => $v}
                            <option value="{$v.id}"{if $v.id== $goods_info.category_id} selected="selected"{/if}>{$v.title}</option>
                            {/foreach}
                        </select>
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>请选择商品分类</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">商品标题：</label></th>
                    <td>
                        <input name="info[title]" style="width:490px;" value="{$goods_info.title}" type="text" class="add-f-ipt1 js_title">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>商品标题会显示在相应内容的标题位置，最多输入 <span style="color:red;">30</span> 字，还可输入 <span class="js_titleNum" style="color:red;">30</span> 字</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">商品单位：</label></th>
                    <td>
                        <select class="add-f-slt1 js_goodsUnit" name="info[unit]">
                            {foreach goods_config::$unit as $k=>$v}
                            <option value="{$v}"{if $v== $goods_info.unit} selected="selected"{/if}>{$v}</option>
                            {/foreach}
                        </select>
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>选择并设置商品的单位</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">成本：</label></th>
                    <td>
                        <input name="info[cost]" style="width:100px;" type="number" step="0.01" class="add-f-ipt1 js_cost" value="{$goods_info.cost}">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>生产成本</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">出厂价格：</label></th>
                    <td>
                        <input name="info[price]" style="width:100px;" type="number" step="0.01" class="add-f-ipt1 js_price" value="{$goods_info.price}">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>一级经销商供货价，价格必须在1元-999999999元之间。</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">终端供货价格：</label></th>
                    <td>
                        <input name="info[market_price]" style="width:100px;" type="number" step="0.01" class="add-f-ipt1 js_market_price" value="{$goods_info.market_price}">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>终端销售指导价，价格必须在1元-999999999元之间。</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">差价：</label></th>
                    <td>
                        <input name="info[diff_price]" style="width:100px;" type="number" step="0.01" class="add-f-ipt1 js_diff_price" value="{$goods_info.diff_price}">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>二级经销商差价</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">抱抱币：</label></th>
                    <td>
                        <input name="info[bbcoin]" style="width:100px;" type="number" class="add-f-ipt1 js_bbcoin" value="{$goods_info.bbcoin}">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>抱抱币兑换价格，留空则设置为与出厂价(并忽略小数位)，"0"表示不可兑换@蒙大统领</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">差币：</label></th>
                    <td>
                        <input name="info[diff_bbcoin]" style="width:100px;" type="number" class="add-f-ipt1 js_diff_bbcoin" value="{$goods_info.diff_bbcoin}">
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>二级经销商抱抱币兑换差价，只回收，不返还一级经销商</div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">体积：</label></th>
                    <td>
                        <input name="info[cube]" style="width:100px;" type="number" step="0.000001" class="add-f-ipt1 stock-input" value="{$goods_info.cube}">
                        <div class="tips">
                            <span style="line-height: 34px;color: #f00;margin-right: 10px;">单位:m³</span>
                            商品体积, 用于估算运输体积
                        </div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">重量：</label></th>
                    <td>
                        <input name="info[weight]" style="width:100px;" type="number" step="0.001" class="add-f-ipt1 stock-input" value="{$goods_info.weight}">
                        <div class="tips">
                            <span style="line-height: 34px;color: #f00;margin-right: 10px;">单位:kg</span>
                            商品重量, 用于估算运输重量
                        </div>
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">商品数量：</label></th>
                    <td>
                        <input name="info[stock]" style="width:100px;" value="{$goods_info.stock}" type="text" class="add-f-ipt1 stock-input js_stock">
                        <div class="tips">
                            <span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>商品总数量(暂不实用)
                        </div>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><label class="add-f-label">商品图片：</label></th>
                    <td class="perUpOuter js_upCover">
                        <div id="queue" style="display:none;width:0px;height:0px;"></div>
                        <div class="clearfix">
                            <div class="btn-upload left js_upButtonParent">
                                <!-- <a href="javascript:void(0);"><i class="icon-upload"></i>上传图片</a> -->
                                <!-- class="js_cover js_upFile js_upPicButton" -->
                                <input id="file_upload" name="tmp_file" type="file" multiple="true">
                            </div>
                        </div>
                        <div class="js_upFileBox" id="js_upPicBox" style="display:none"></div>
                        <div class="picBox" id="queue">
                            {$goods_image_list = goods_helper::get_goods_image_list($id)}
                           {if $goods_image_list}
                            {foreach $goods_image_list as $image_k=>$image_v}
                           {if $image_v.id == $goods_info.cover}
                            <div class="js_upPic js_picNum_0" have-data="1" pic-data="0" is-cover="1">
                                <i class="cover-style">封面图</i>
                                <span class="delete-btn js_delPic">×</span>
                                <img src='{_image($image_v.path,"small")}'>
                            </div>
                            <input type="hidden" class="js_image" name="cover" title-data="{$image_v.title}" value="{$image_v.id}">
                            {else}
                            <div class="js_upPic js_picNum_{$image_k+1}" have-data="1" pic-data="{$image_k+1}" is-cover="0">
                                <span class="main-btn js_setCover">设为封面</span>
                                <span class="delete-btn js_delPic">×</span>
                                <img src='{_image($image_v.path,"small")}'>
                            </div>
                            <input type="hidden" class="js_image" title-data="{$image_v.title}" value="{$image_v.id}" name="image[]">
                           {/if}
                            {/foreach}
                           {if $image_k < 4}
                            {for $foo=1 to 5-$image_k}
                            <div class="js_upPic js_picNum_{$image_k+$foo+1}" have-data="0" pic-data="{$image_k+$foo+1}"></div>
                            {/for}
                            {else}
                            <div class="js_upPic js_picNum_{$image_k+2}" have-data="0" pic-data="{$image_k+2}"></div>
                           {/if}
                            {else}
                            <div class="js_upPic js_picNum_0" have-data="0" pic-data="0">
                                <span style="line-height: 90px;color: #f00;margin-right: 5px;">*</span><span style="line-height: 90px;font-size:12px;">封面图</span>
                            </div>
                            <div class="js_upPic js_picNum_1" have-data="0" pic-data="1"></div>
                            <div class="js_upPic js_picNum_2" have-data="0" pic-data="2"></div>
                            <div class="js_upPic js_picNum_3" have-data="0" pic-data="3"></div>
                            <div class="js_upPic js_picNum_4" have-data="0" pic-data="4"></div>
                            <div class="js_upPic js_picNum_5" have-data="0" pic-data="5"></div>
                           {/if}
                        </div>
                        <div class="tips" style="clear:both"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>第一张图片为封面图，必须上传。标准尺寸497px*333px</div>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><label class="add-f-label">商品简介：</label></th>
                    <td>
                        <textarea class="add-f-area js_intro" name="info[intro]">{$goods_info.intro}</textarea>
                        <div class="tips">商品简介会显示在相应内容的简介位置，最多输入 <span style="color:red;">200</span> 字，还可输入 <span class="js_introNum" style="color:red;">200</span> 字</div>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><label class="add-f-label">商品内容：</label></th>
                    <td>
                        <textarea class="js_content" name="info[content]" id="js_editor" style="width:490px;">{$goods_info.content}</textarea>
                        <div class="tips"><span style="line-height: 34px;color: #f00;margin-right: 10px;">*</span>商品内容会显示在详情页显示，图片标准宽740px，高不超过1400px</div>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><span class="add-f-label">是否推荐：</span></th>
                    <td>
                        <label class="add-f-label">
                            <input type="radio" name="info[is_recommend]" value="1" class="add-f-radio"{if $goods_info.is_recommend== 1}checked="checked"{/if}>是
                        </label>&nbsp;&nbsp;
                        <label class="add-f-label">
                            <input type="radio" name="info[is_recommend]" value="0" class="add-f-radio"{if $goods_info.is_recommend== 0}checked="checked"{/if}>否
                        </label>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><span class="add-f-label">是否热门：</span></th>
                    <td>
                        <label class="add-f-label">
                            <input type="radio" name="info[is_hot]" value="1" class="add-f-radio"{if $goods_info.is_hot== 1}checked="checked"{/if}>是
                        </label>&nbsp;&nbsp;
                        <label class="add-f-label">
                            <input type="radio" name="info[is_hot]" value="0" class="add-f-radio"{if $goods_info.is_hot== 0}checked="checked"{/if}>否
                        </label>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><span class="add-f-label">是否上架：</span></th>
                    <td>
                        <label class="add-f-label">
                            <input type="radio" name="info[is_sale]" value="1" class="add-f-radio"{if $goods_info.is_sale== 1}checked="checked"{/if}>立即上架
                        </label>&nbsp;&nbsp;
                        <label class="add-f-label">
                            <input type="radio" name="info[is_sale]" value="0" class="add-f-radio"{if $goods_info.is_sale== 0}checked="checked"{/if}>放入仓库
                        </label>
                    </td>
                </tr>
                <tr>
                <tr>
                    <!-- 商品下架以后，是否还可以盘点库存 -->
                    <th valign="top"><span class="add-f-label">盘点库存：</span></th>
                    <td>
                        <label class="add-f-label">
                            <input type="radio" name="info[is_init]" value="1" class="add-f-radio"{if $goods_info.is_init== 1}checked="checked"{/if}>允许
                        </label>&nbsp;&nbsp;
                        <label class="add-f-label">
                            <input type="radio" name="info[is_init]" value="0" class="add-f-radio"{if $goods_info.is_init== 0}checked="checked"{/if}>禁止
                        </label>
                    </td>
                </tr>
                <tr>
                    <th valign="top"><span class="add-f-label">商品渠道：</span></th>
                    <td>
                        {foreach $channel_list as $v}

                        <label class="add-f-label">
                            <input type="checkbox" name="channel_ids[]" value="{$v.id}" class="add-f-radio"
                                   {foreach $select_channel_list as $val}
                                  {if $val.channel_id== $v.id}checked="checked"{/if}
                            {/foreach}
                            >{$v.title}
                        </label>&nbsp;&nbsp

                        {/foreach}
                    </td>
                </tr>
                <tr>
                    <th><label class="add-f-label">商品排序：</label></th>
                    <td>
                        <input name="info[view_order]" style="width:100px;" value="{$goods_info.view_order}" type="text" class="add-f-ipt1">
                        <div class="tips">数字越大，排位越靠前</div>
                    </td>
                </tr>
                <tr>
                    <th>&nbsp;</th>
                    <td class="noborder">
                        <button type="submit" class="btn btn-success js_submit">&nbsp;&nbsp;&nbsp;确认&nbsp;&nbsp;&nbsp;</button>
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>

<!--end:商品新增-->
{load_js file='ueditor1_4_3/ueditor.config.js'}
{load_js file='ueditor1_4_3/ueditor.all.js'}
{load_js file="uploadify/jquery.uploadify.min.js"}
<script>
    var resName = 'goods';
    /* function setNum(thisClass, maxNum) {
     var presentNum = getFontNum($('.'+thisClass).val());
     var remainNum  = maxNum - presentNum;
     if (remainNum < 0) {
     $('.'+thisClass).val(cutStr($('.'+thisClass).val(),maxNum));
     }
     $('.'+thisClass+'Num').text(remainNum);
     } */
    function setNum(thisClass, maxNum) {
        var presentNum = $('.' + thisClass).val().length;
        var remainNum = maxNum - presentNum;
        if (remainNum < 0) {
            $('.' + thisClass).val($('.' + thisClass).val().substr(0, maxNum));
            $('.' + thisClass + 'Num').text(0);
        } else {
            $('.' + thisClass + 'Num').text(remainNum);
        }
    }

    // 通过属性id 获取属性值列表
    var valueGroupId = 0;
    function check_value(propertyId, propertyTitle) {
        $.post("{Anurl('property/admin/check_value')}", {
            property_id: propertyId
        }, function (data) {
            if (data.info == 'ok') {
                valueGroupId++;
                $('.js_propertyGroup').append('<div style="height:1px;width580px;margin-top:10px;clear:both;"></div>');
                $('.js_propertyGroup').append('<input type="hidden" name="sku[property][]" value="' + propertyId + '">');
                $('.js_propertyGroup').append('<b style="margin-top:10px;">' + propertyTitle + '</b>：');
                /* if (propertyTitle == '颜色') {
                 $('.js_propertyGroup').append('<input type="checkbox" class="js_isIcon" parent-id="'+valueGroupId+'"><span style="color:#AAAAAA;font-size:12px;" class="js_isIconText">是否展示小图标</span>');
                 } else {
                 $('.js_propertyGroup').append('<input type="checkbox" style="display:none;" class="js_isIcon" parent-id="'+valueGroupId+'">');
                 } */
                $('.js_propertyGroup').append('<input type="checkbox" class="js_isIcon" parent-id="' + valueGroupId + '"><span style="color:#AAAAAA;font-size:12px;" class="js_isIconText">是否展示小图标</span>');
                $('.js_propertyGroup').append('<div style="height:1px;width580px;margin-bottom:5px;clear:both;"></div>');

                var dataLength = data.value_list.length;
                for (var i = 0; i < dataLength; i++) {
                    $('.js_propertyGroup').append('<div style="width:190px;height:20px;float:left;margin-bottom:10px;margin-top:10px;"><input type="checkbox" class="js_sltValue js_valueGroup_' + valueGroupId + ' js_value_' + data.value_list[i]['id'] + '" parent-id="' + valueGroupId + '" name="sku[value][]" value="' + data.value_list[i]['id'] + '" style="margin-right:5px;"><span class="js_valueTitle_' + data.value_list[i]['id'] + '" ctag="js_sltValue">' + data.value_list[i]['value'] + '</span></div>');
                }
                $('.js_propertyGroup').append('<div style="height:1px;width580px;margin-bottom:10px;clear:both;"></div>');
            }
            ;
        }, 'json');
    }

    $(function () {
        var priceArr = {};
        var stockArr = {};
        var imageArr = {};


        $('.js_flagship').click(function () {
            if (this.value == 1) {
                var link = $('.js_flagship_link').data('link');
                $('.js_flagship_link').show().find('input').val(link);
            } else {
                $('.js_flagship_link').hide().find('input').val('');
            }
        })

       {if $sku_property_list}
        // 赋值。
        getValue('js_skuPrice', priceArr);
        getValue('js_skuStock', stockArr);
        getImage(imageArr);
        var cols = $('.js_isIcon').length;
        var rows = $('.js_skuPrice').length;
        mergeTable(cols, rows);
       {/if}
        // 默认库存量
        $('.js_stock').attr('readonly', false);

        // 选择销售属性
        $('.js_propertyGroup').on('click', '.js_sltPropertyText', function () {
            var inputBox = $(this).prev();
            if (inputBox.attr('checked') == 'checked') {
                inputBox.attr('checked', false);
            } else {
                inputBox.attr('checked', true);
            }
        });
        var selProperty = $('.js_propertyGroup').html();
        $('.js_propertyGroup').on('click', '.js_sureProerty', function () {
            var propertyId = new Array();
            var propertyTitle = new Array();
            var n = 0;
            $('.js_sltProperty').each(function () {
                if ($(this).attr('checked') == 'checked') {
                    propertyId[n] = $(this).val();
                    propertyTitle[n] = $(this).attr('title-data');
                    n++;
                }
                ;
            });
            if (propertyId == '') {
                showMsg('请选择属性!');
                return;
            }
            ;

            $('.js_goodsSkuCode').hide();
            $('.js_goodsSkuName').hide();
            $('.js_propertyGroup').html('');
            $('.js_propertyInfo').html('');
            $('.js_propertyGroup').append('<div style="position:absolute;top:0px;right:0px;"><span class="btn btn-xs btn-default js_returnProperty">重新选择规格</span></div>');
            var idLength = propertyId.length;
            for (var i = 0; i < idLength; i++) {
                check_value(propertyId[i], propertyTitle[i]);
            }
        });

        // 重新选择规格
        $('.js_propertyGroup').on('click', '.js_returnProperty', function () {
            showConfirm('重新选择规格将删除现有已设置的所有规格数据！', 0, function () {
                $('.js_propertyGroup').html($('.js_propertyList').html());
                $('.js_iconGroup').html('');
                $('.js_skuGroup').html('');
                $('.js_stock').val('');
                $('.js_goodsSkuCode').show();
                $('.js_goodsSkuName').show();
                $('.js_stock').attr('readonly', false);
                $('.js_propertyInfo').css('display', 'block');
                $('.js_propertyInfo').html('请选择当前商品的规格');
                priceArr = {};
                stockArr = {};
            });
        });

        // 是否启用小图标
        $('.js_propertyGroup').on('click', '.js_isIcon, .js_isIconText', function () {
            var iconInput = $(this);
            if ($(this).attr('class') == 'js_isIconText') {
                iconInput = $(this).prev();
                if (iconInput.attr('checked') == 'checked') {
                    iconInput.attr('checked', false);
                } else {
                    iconInput.attr('checked', 'checked');
                }
            }
            if (iconInput.attr('checked') == 'checked') {
                $('.js_isIcon').each(function () {
                    $(this).attr('checked', false);
                });
                iconInput.attr('checked', true);

                var iconGroupTitle = iconInput.prev().html();
                var valueParentId = iconInput.attr('parent-id');

                // 组装表格
                $('.js_iconGroup').html('');
                $('.js_iconGroup').parent().css('display', 'block');
                $('.js_iconGroup').attr('parent-id', valueParentId);
                $('.js_iconGroup').append('<tr><th style="width:25%;">' + iconGroupTitle + '</th><th>图片（无图片可不填）标准宽40px*150px</th></tr>');
                $('.js_valueGroup_' + valueParentId).each(function () {
                    if ($(this).attr('checked') == 'checked') {
                        var iconTitle = $(this).next().val();
                        var iconId = $(this).val();
                        $('.js_iconGroup').append('<tr value-data="' + iconId + '"><td id-data="' + iconId + '">' + iconTitle + '</td><td class="perUpOuter"><div class="btn-upload"><a href="javascript:void(0);"><i class="icon-upload"></i>上传封面</a><input class="js_upFile"  type="file" name="icon[' + iconId + ']" img-data="' + iconId + '"></div><div class="js_upFileBox" style="margin-top:0px;margin-left:8px;"></div></td></tr>');
                    }
                    ;
                });
            } else {
                $('.js_isIcon').each(function () {
                    $(this).attr('checked', false);
                });
                iconInput.attr('checked', false);
                if ($('.js_iconGroup').parent().css('display') == 'block') {
                    $('.js_iconGroup').parent().css('display', 'none');
                }
            }
        });

        // 选择属性值出现输入框
        var valueList = new Array();  // 用于恢复选中
        var tmpList = new Array();
        $('.js_propertyGroup').on('click', '.js_sltValue, .js_sltValue+span', function () {
            var inputBox = $(this);
            if ($(this).attr('ctag') == 'js_sltValue') {
                inputBox = $(this).prev();
                if (inputBox.attr('checked') == 'checked') {
                    inputBox.attr('checked', false);
                } else {
                    inputBox.attr('checked', 'checked');
                }
            }
            getImage(imageArr);
            var valueId = inputBox.val();
            if (inputBox.next().html()) {
                valueList[valueId] = inputBox.next().html();
                var values;
                if (tmpList[valueId]) {
                    values = tmpList[valueId];
                } else {
                    values = valueList[valueId];
                }
                inputBox.next().remove();
                inputBox.after('<input class="js_inputValue" style="width:160px;" type="text" name="sku[tmp_value][' + valueId + ']" value="' + values + '">');

                // 添加icon框
                if (inputBox.attr('parent-id') == $('.js_iconGroup').attr('parent-id') && !$('tr[value-data=' + valueId + ']').length) {
                    $('.js_iconGroup').append('<tr value-data="' + valueId + '"><td valueid-data="' + valueId + '">' + values + '</td><td class="perUpOuter"><div class="btn-upload"><a href="javascript:void(0);"><i class="icon-upload"></i>上传封面</a><input class="js_upFile"  type="file" name="icon[' + valueId + ']" img-data="' + valueId + '"></div><div class="js_upFileBox" style="margin-top:0px;margin-left:8px;"></div></td></tr>');
                }
            } else {
                tmpList[valueId] = inputBox.next().val();
                var currValue;
                if (typeof(valueList[valueId]) == 'undefined') {
                    currValue = tmpList[valueId];
                } else {
                    currValue = valueList[valueId];
                }
                inputBox.next().remove();
                inputBox.after('<span class="js_valueTitle_' + valueId + '" ctag="js_sltValue">' + currValue + '</span>');
                $('tr[value-data=' + valueId + ']').remove();
            }

            // 添加sku属性
            toggleSku();

            // 循环赋值
            setValue('js_skuPrice', priceArr);
            setValue('js_skuStock', stockArr);
            setImage(imageArr);
        });

        // 改变属性值时，下面的名称跟这改变
        $('.js_propertyGroup').on('blur', '.js_inputValue', function () {
            var currTitle = $(this).val();
            var currId = $(this).prev().val();
            $('td[id-data=' + currId + '],td[valueid-data=' + currId + ']').each(function () {
                $(this).html(currTitle);
            });
        });

        // 预览icon
        $('.js_iconGroup').on('change', '.js_upFile', function () {
            handleFileSelect($(this));
            getImage(imageArr);
        });

        // 预览skuCover
        $('.js_skuGroup').on('change', '.js_upFile', function () {
            handleFileSelect($(this));
            getImage(imageArr);
        });

        // 判断输入是否位数字，不为数字自动转为数字
        $('.js_skuGroup').on('keyup', '.js_inputNum', function () {
            autoNum($(this));
        });
        $('.js_skuGroup').on('blur', '.js_inputFloat', function () {
            autoFloat($(this));
        });

        // 自动转为数字
        $('.js_stock').keyup(function () {
            autoNum($(this));
        });

        // 存储已输入的表单数据 和 记录总数量
        var numTotal;
        $('.js_skuGroup').on('keyup', '.js_skuPrice', function () {
            var currValue = $(this).val();
            var currIndex = $(this).attr('ids-data');
        });
        $('.js_skuGroup').on('blur', '.js_skuPrice', function () {
            var currValue = $(this).val();
            var currIndex = $(this).attr('ids-data');
            priceArr[currIndex] = currValue;
        });
        $('.js_skuGroup').on('blur', '.js_skuStock', function () {
            var currValue = $(this).val();
            var currIndex = $(this).attr('ids-data');
            stockArr[currIndex] = currValue;

            // 循环计算 总数量
            numTotal = 0;
            $('.js_skuStock').each(function () {
                var currStock = parseInt($(this).val());
                if (isNaN(currStock)) {
                    currStock = 0;
                }
                ;
                numTotal += currStock;
            });

            $('.js_stock').val(numTotal);
            $('.js_stock').attr('readonly', true);
        });

        // 批量上传图片
        setTimeout(function () {
            $('#file_upload').uploadify({
                'swf': siteUrl + '/js/uploadify/uploadify.swf',
                'uploader': '{AnUrl("core/handler/file_uploader/uploadify")}',
                'queueID': 'queue',
                'width': '106',
                'height': '30',
                'buttonText': '上传图片',
                'formData': {
                    'res_name': "goods",
                    'res_id': '{if $id}{$id}{else}0{/if}'
                },
                'onUploadStart': function (fileObj) {
                    var myself = this;
                    if (checkFileNames(fileObj.name)) {
                        showMsg("已存在名为:" + fileObj.name + "的文件，请重新选择文件！");
                        myself.cancelUpload(fileObj.id);
                    }
                },
                'onUploadSuccess': function (error, content) {
                    addSpace();
                    var image = JSON.parse(content);
                    var imgPath = image.small;
                    var fileId = image.id;
                    if (imgPath.indexOf('http:') == -1) {
                        var img = '<img src="' + siteUrl + imgPath + '" />';
                    } else {
                        var img = '<img src="' + imgPath + '" />';
                    }

                    var picData = '';
                    $('.js_upPic').each(function () {
                        if ($(this).attr('have-data') == 0) {
                            picData = $(this).attr('pic-data');
                            return false;
                        }
                        ;
                    });
                    $('.js_picNum_' + picData).html(img);
                    $('.js_picNum_' + picData).prepend('<span class="delete-btn js_delPic">×</span>');
                    $('.js_picNum_' + picData).after('<input type="hidden" name="image[]" class="js_image" title-data="' + image.title + '" value="' + fileId + '">');
                    if ($('.js_upPic[have-data=1]').length > 0) {
                        if ($('.js_picNum_' + picData).attr('is-cover') == 1) {
                            $('.js_picNum_' + picData).next().attr('name', 'cover');
                            $('.js_picNum_' + picData).prepend('<i class="cover-style">封面图</i>');
                        } else {
                            $('.js_picNum_' + picData).prepend('<span class="main-btn js_setCover">设为封面</span>');
                        }
                    } else {
                        $('.js_picNum_' + picData).next().attr('name', 'cover');
                        $('.js_picNum_' + picData).prepend('<i class="cover-style">封面图</i>');
                        $('.js_picNum_' + picData).attr('is-cover', 1);
                    }
                    $('.js_picNum_' + picData).attr('have-data', 1);
                },
                'onError': function (event, ID, fileObj, errorObj) {
                    if (errorObj.type === "File Size") {
                        showMsg('超过文件上传大小限制（2M）！');
                        return;
                    }
                    showMsg(errorObj.type + ', Error: ' + errorObj.info);
                }
            });
        }, 10);

        // 删除需要上传的图片
        $('.picBox').on('click', '.js_delPic', function () {
            // 删除后台数据
            var delPic = $(this).parent();
            var fileId = delPic.next().val();
            var resId ={if $id}{$id}{else}0{/if};
            var isDelete = 1;
            var isCover = 0;
            var currCoverId;

            // 删除前台数据
            if (delPic.next().attr('name') == 'cover') {
                isCover = 1;
            }
            ;

            delPic.attr('have-data', 0);
            delPic.html('');
            if (delPic.next().val()) {
                delPic.next().remove();
            }
            ;

            if ($('.js_upPic[have-data=1]').length > 0) {
                currCoverId = $('.js_upPic[have-data=1]').eq(0).next().attr('value');
            }

            // 删除后台数据
            $.get("{Anurl('goods/admin/delete_res')}", {
                file_id: fileId,
                res_name: 'goods',
                res_id: resId,
                is_cover: isCover,
                cover: currCoverId
            }, function (data) {
                if (data.info != 'ok') {
                    isDelete = 0;
                }
            }, 'json');
            if (!isDelete) {
                showMsg('数据删除失败');
                return;
            }
            ;

            delSpace();

            if ($('.js_upPic[have-data=1]').length > 0) {
                if (isCover == 1) {
                    var currCover = $('.js_upPic[have-data=1]').eq(0);
                    currCover.attr('is-cover', 1);
                    currCover.next().attr('name', 'cover');
                    currCover.prepend('<i class="cover-style">封面图</i>');
                    currCover.find('.js_setCover').remove();
                    delPic.attr('is-cover', 0);
                }
            } else {
                $('.js_upPic').eq(0).append('<span style="line-height: 90px;color: #f00;margin-right: 5px;">*</span><span style="line-height: 90px;font-size:12px;">封面图</span>');
            }

        });

        // 设为封面图
        $('.picBox').on('click', '.js_setCover', function () {
            var oldCover = $('.js_upPic[is-cover=1]');
            var currCover = $(this).parent();
            oldCover.attr('is-cover', 0);
            oldCover.next().attr('name', 'image[]');
            oldCover.append('<span class="main-btn js_setCover">设为封面</span>');
            oldCover.find('.cover-style').remove();
            currCover.attr('is-cover', 1);
            currCover.next().attr('name', 'cover');
            currCover.prepend('<i class="cover-style">封面图</i>');
            currCover.find('.js_setCover').remove();

           {if $id}
            var fileId = currCover.next().attr('value');
            var goodsId = "{$id}";
            setCover(goodsId, fileId);
           {/if}
        });

        // 初始化编辑器
        var editor = new UE.ui.Editor({
            serverUrl: "{AnUrl('core/handler/file_uploader?source=ueditor&file_field=Filedata')}",
            initialFrameWidth: 820,
            initialFrameHeight: 450,
            elementPathEnabled: false,
            autoHeightEnabled: false,
            autoFloatEnabled: false,
            wordCount: false,
            toolbars: [['fullscreen', 'source', "undo", "redo", "justifyleft", "justifycenter", "justifyright", "justifyjustify", "lineheight", "bold", "italic", "underline", "strikethrough", "fontsize", "fontfamily", "backcolor", "forecolor", "superscript", "subscript", "insertorderedlist", "insertunorderedlist", "insertimage", "inserttable", "emotion", "spechars", "unlink", "link"], []]
        });
        editor.render("js_editor");

        // 初始化剩余字数
        setNum('js_title', 30);
        $('.js_title').keyup(function () {
            setNum('js_title', 30);
        });
        setNum('js_intro', 200);
        $('.js_intro').keyup(function () {
            setNum('js_intro', 200);
        });

        // 提交验证
        $('.js_submit').click(function (e) {
            e.preventDefault();
            var category = $('.js_category').val();
            var title = $.trim($('.js_title').val());
            var cost = $.trim($('.js_cost').val());
            var price = $.trim($('.js_price').val());
            var stock = $.trim($('.js_stock').val());
            //var bbcoin       = $.trim($('.js_bbcoin').val());
            var content = $.trim(editor.getContent());

            if (category == '' || category < 0) {
                showMsg('请选择分类');
                return;
            }
            if (!cost) {
                showMsg('价格不能为空');
                return;
            }
            if (!title) {
                showMsg('标题不能为空');
                return;
            }
            if (!price) {
                showMsg('价格不能为空');
                return;
            }

            if ($('.js_skuPrice')) {
                var isRight = 1;
                $('.js_skuPrice').each(function () {
                    var priceValue = $(this).val();
                    var idsData = $(this).attr('ids-data');
                    var stockValue = $('.js_skuStock[ids-data=' + idsData + ']').val();
                    if ((priceValue == '' || priceValue == 0) && stockValue > 0) {
                        isRight = 0;
                        return;
                    }
                    ;
                });
                if (!isRight) {
                    showMsg('商品规格的价格和库存填写不完整');
                    return;
                }
                ;
            }

            if (stock == '' || stock < 0) {
                showMsg('库存不能为空');
                return;
            }

            if ($('.js_upPic[is-cover=1]').length < 1) {
                showMsg('封面图不能为空');
                return;
            }

            if (!content) {
                showMsg('内容不能为空');
                return;
            }
            var askTitle = 0;
            var askAnswer = 0;
            $('.ask-title').each(function () {
                if (!this.value) {
                    askTitle++;
                }
            })
            $('.ask-answer').each(function () {
                if (!this.value) {
                    askAnswer++;
                }
            })
            $('.js_content').val(content);
            $('.js_creatForm').submit();
        });
    });

    function toggleSku() {
        // 判断当前选择了几个属性
        var propertyNum = $('.js_isIcon').length;
        var sltProperty = 0;
        var sltArr = new Array();
        $('.js_sltValue').each(function () {
            if ($(this).attr('checked') == 'checked') {
                var parentId = $(this).attr('parent-id');
                if (!in_array(parentId, sltArr)) {
                    sltArr[parentId] = parentId;
                    sltProperty++;
                }
                ;
            }
            ;
        });

        if (sltProperty != propertyNum) {
            $('.js_propertyInfo').css('display', 'block');
            $('.js_propertyInfo').html('您需要选择所有的销售属性，才能组合成完整的规格信息。');
            $('.js_skuGroup').parent().css('display', 'none');
            $('.js_skuGroup').html('');
            $('.js_stock').val('');
            $('.js_stock').attr('readonly', false);
            return false;
        }
        ;
        $('.js_propertyInfo').css('display', 'none');

        // 循环计算 总数量
        numTotal = 0;
        $('.js_skuStock').each(function () {
            var currStock = parseInt($(this).val());
            if (isNaN(currStock)) {
                currStock = 0;
            }
            ;
            numTotal += currStock;
        });

        $('.js_stock').val(numTotal);
        $('.js_stock').attr('readonly', true);

        // 遍历生成sku属性
        var valueParentIds = new Array();
        var valueParentTitles = new Array();
        var valueJsonIds = [];
        var valueJsonTitle = [];
        $('.js_isIcon').each(function () {
            var parentTitle = $(this).prev().html();
            var parentId = $(this).attr('parent-id');
            valueParentIds.push(parentId);
            valueParentTitles.push(parentTitle);
            var valueIds = new Array();
            $('.js_valueGroup_' + parentId).each(function () {
                if ($(this).attr('checked') == 'checked') {
                    valueIds.push($(this).val());
                }
                ;
            });
            valueJsonIds.push(valueIds);
        });

        // 多个域笛卡尔积计算 求值
        var valueResult = new Array();

        function toResult(arrIndex, aresult) {
            if (arrIndex >= valueJsonIds.length) {
                valueResult.push(aresult);
                return;
            }
            ;

            var aArr = valueJsonIds[arrIndex];
            if (!aresult)
                aresult = new Array();

            for (var i = 0; i < aArr.length; i++) {
                var theResult = aresult.slice(0, aresult.length);
                theResult.push(aArr[i]);
                toResult(arrIndex + 1, theResult);
            }
        }

        toResult(0);

        // 生成标题
        var skuTitle;
        for (var i in valueParentIds) {
            // 拼接标题
            skuTitle += '<th parent-id="' + valueParentIds[i] + '" style="min-width:80px;">' + valueParentTitles[i] + '</th>';
        }
        $('.js_skuGroup').parent().css('display', 'block');
        $('.js_skuGroup').html('');
        $('.js_skuGroup').append('<tr>' + skuTitle + '<th style="min-width:65px;"><span style="line-height: 25px;color: #f00;margin-right: 10px;">*</span>价格</th><th style="min-width:65px;"><span style="line-height: 25px;color: #f00;margin-right: 10px;">*</span>数量</th><th style="min-width:150px;">封面图标准900px*900px</th></tr>');

        // 生成属性列表
        for (var i in valueResult) {
            var skuList = '';
            var currIds = new Array();
            for (var j in valueResult[i]) {
                var valueTitle = $('.js_value_' + valueResult[i][j]).next().val();
                skuList += '<td class="js_tableTd_' + i + '_' + j + '" id-data="' + valueResult[i][j] + '">' + valueTitle + '</td>';
                currIds.push(valueResult[i][j]);
            }
            var idsInfo = currIds.join('-');
            $('.js_skuGroup').append('<tr>' + skuList + '<td><input class="js_inputFloat js_skuPrice" ids-data="' + idsInfo + '" type="text" name="sku[price][' + idsInfo + ']"></td><td><input class="js_inputNum js_skuStock" ids-data="' + idsInfo + '" type="text" name="sku[stock][' + idsInfo + ']"></td><td class="perUpOuter"><div class="btn-upload"><a href="javascript:void(0);" style="width:90px;"><i class="icon-upload"></i>上传封面</a><input class="js_upFile" type="file" name="sku_cover[' + idsInfo + ']" img-data="' + idsInfo + '"></div><div class="js_upFileBox" style="margin-top:0px;margin-left:8px;"></div></td></tr>');
        }

        // 合并表格
        var rows = $('.js_skuPrice').length;
        mergeTable(propertyNum, rows);
    }

    // 判断某数是否在数组中
    function in_array(search, array) {
        for (var i in array) {
            if (array[i] == search) {
                return true;
            }
        }
        return false;
    }

    // 自动转为数字
    function autoNum(obj) {
        var currNum = obj.val();
        currNum = parseInt(currNum);
        if (isNaN(currNum)) {
            currNum = 0;
        }
        ;
        obj.val(currNum);
    }
    function autoFloat(obj) {
        var currNum = obj.val();
        currNum = parseFloat(currNum);
        if (isNaN(currNum)) {
            currNum = 0;
        }
        ;
        obj.val(currNum.toFixed(2));
    }

    // 添加空白图片
    function addSpace() {
        var maxPicData = new Array();
        var needSpace = 0;
        $('.js_upPic').each(function () {
            var picData = $(this).attr('pic-data');
            maxPicData.push(picData);
            if ($(this).attr('have-data') == 1) {
                needSpace++;
            }
        });

        var maxData = Math.max.apply(null, maxPicData);
        if (maxData - needSpace < 1) {
            var value = maxData + 1;
            $('.js_picNum_' + maxData).after('<div class="js_upPic js_picNum_' + value + '" have-data="0" is-cover="0" pic-data="' + value + '"></div>');
        }
        ;
    }
    // 删除空白图片
    function delSpace() {
        var maxPicData = new Array();
        var endSpace = 0;
        $('.js_upPic').each(function () {
            var picData = $(this).attr('pic-data');
            maxPicData.push(picData);
            if ($(this).attr('have-data') == 1) {
                endSpace = 0;
            } else {
                endSpace++;
            }
        });

        var maxData = Math.max.apply(null, maxPicData);
        if (endSpace > 1 && maxData > 5) {
            var delNum = 0;
            if (maxData - endSpace + 1 < 6) {
                delNum = 5;
            } else {
                delNum = maxData - endSpace + 1;
            }
            for (var i = maxData; i > delNum; i--) {
                $('.js_picNum_' + i).remove();
            }
        }
    }

    // 循环取值
    function getValue(element, valueArr) {
        $('.' + element).each(function () {
            var currValue = $(this).val();
            var currIndex = $(this).attr('ids-data');
            valueArr[currIndex] = currValue;
        });
    }

    // 循环赋值
    function setValue(element, valueArr) {
        $('.' + element).each(function () {
            var currIndex = $(this).attr('ids-data');
            $(this).val(valueArr[currIndex]);
        });
    }

    // 循环取出图片
    function getImage(imageArr) {
        $('.js_upFile').each(function () {
            var currIndex = $(this).attr('img-data');
            var currValue = $(this).closest('.perUpOuter').html();
            imageArr[currIndex] = currValue;
        });
    }

    // 循环设置图片
    function setImage(imageArr) {
        $('.js_upFile').each(function () {
            var currIndex = $(this).attr('img-data');
            var thisclosest = $(this).closest('.perUpOuter');
            thisclosest.html(imageArr[currIndex]);
        });
    }

    // 合并表格
    function mergeTable(cols, rows) {
        for (var j = 0; j < cols - 1; j++) {
            var firstI = 0;
            var rowsPan = 0;
            for (var i = 0; i < rows; i++) {
                var firstTd = $('.js_tableTd_' + firstI + '_' + j);
                if (firstTd.html() == $('.js_tableTd_' + i + '_' + j).html()) {
                    rowsPan++;
                    if (firstI != i) {
                        firstTd.attr('rowspan', rowsPan);
                        $('.js_tableTd_' + i + '_' + j).remove();
                    }
                    ;
                } else {
                    firstI = i;
                    rowsPan = 1;
                }
            }
        }
    }

    // 判断文件名是否重复
    function checkFileNames(fileName) {
        var isR = 0;
        $('.js_image').each(function () {
            var imageTitle = $(this).attr('title-data');
            if (imageTitle == fileName) {
                isR = 1;
                return;
            }
        });
        if (isR == 1) {
            return true;
        } else {
            return false;
        }
    }

    // 设置封面图
    function setCover(goodsId, fileId) {
        $.get("{AnUrl('goods/admin/set_cover')}", {
            file_id: fileId,
            goods_id: goodsId
        }, function (data) {
            if (data.info != 'ok') {
                showMsg(data.info);
            }
        }, 'json');
    }
</script>

{include_core file="admin/lib/footer.html"}
